/*
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2022-04-24 10:24:39
 * @FilePath: \puppeteer-demo\scripts\excel.js
 */

import fs from 'fs';
import xlsx from 'xlsx';
const FileName = "test.xls";

/**
 * code返回码枚举
 * 1：正常，2：没有需要提醒的型号，-1：错误。
 */

// 获取第一条还没提醒的数据
function getFirstOne() {
  let obj = getObj();
  let item = {};

  for (let i = 0; i < obj.length; i++) {
    item = obj[i];
    if (item.isRemind == "否") {
      item.url =
        "https://www.ti.com.cn/store/ti/zh/p/product/?p=" +
        item.productNum +
        "&keyMatch=" +
        item.productNum +
        "&tisearch=search-everything&usecase=OPN";

      item.total = obj.length;
      item.ranking = i + 1;
      return item;
    }
  }
  return null;
}

// 设置数据为已提醒
function setOneRemind(body) {
  let {
    productNum,
    isRemind,
    remark
  } = body;
  let obj = getObj();
  let item =null;

  debugger
  try {
    for (let i = 0; i < obj.length; i++) {
      item = obj[i];
      // 处理excel可以存在相同的数据
      if (item.productNum == productNum && item.isRemind == "否") {
        item.isRemind = isRemind;
        item.remark = remark;
        return changeXlsx(item, i);
        break;
      }
    }

    return {
      code: 2,
      msg: `保存Excel时，找不到${productNum}`,
    };
  } catch (error) {
    return {
      code: -1,
      error: dealWithFsError(error),
      msg: "保存到本地文件错误，请尝试关闭excel，然后刷新页面...",
    };
  }
}

function changeXlsx(item, index) {
  let workbook = xlsx.readFile(`./excel/${FileName}`); //workbook就是xls文档对象
  let sheetNames = workbook.SheetNames; //获取表明
  let sheet = workbook.Sheets[sheetNames[0]];

  xlsx.utils.sheet_add_aoa(
    sheet,
    [
      [item.productNum, item.isRemind, item.remark]
    ], {
      origin: {
        r: index + 1,
        c: 0,
      },
    }
  );

  // 将workbook转成buf，再通过fs写入本地
  const buf = xlsx.write(workbook, {
    type: "buffer",
    bookType: "xlsx",
  });
  /* buf is a Buffer */
  fs.writeFileSync(`./excel/${FileName}`, buf);

  return {
    code: 1,
    msg: `修改型号${item.productNum} 是否提醒项：${item.isRemind}，备注项：${item.remark}`,
  };
}

// 获取excel表格数据
function getObj() {
  let workbook = xlsx.readFile(`./excel/${FileName}`); //workbook就是xls文档对象
  let sheetNames = workbook.SheetNames; //获取表明
  let sheet = workbook.Sheets[sheetNames[0]]; //通过表明得到表对象
  var data = xlsx.utils.sheet_to_json(sheet); //通过工具将表对象的数据读出来并转成json
  return data;
}

// 获取第二个sheet的email,即临时保存的需要通知的邮箱
function getEmail() {
  let workbook = xlsx.readFile(`./excel/${FileName}`); //workbook就是xls文档对象
  // console.log(workbook);
  let sheetNames = workbook.SheetNames; //获取表明
  let sheet = workbook.Sheets[sheetNames[1]]; //通过表明得到表对象
  var data = xlsx.utils.sheet_to_json(sheet); //通过工具将表对象的数据读出来并转成json
  return data[0].email;
}

function dealWithFsError(error) {
  let temp = JSON.parse(JSON.stringify(error));
  temp.name = error.code || error.message;
  return temp;
}

export default {
  getFirstOne,
  setOneRemind,
  changeXlsx,
  getObj,
  getEmail,
}